<?php

/**
 * @author dungdhs@gmail.com
 * @copyright 2012
 */

function admin_page_task(){
  return array(
    'default' => array(
      'func'  => '_admin_page_default',
      'perm'  => 'admin page',
      'title' => 'Quản lý trang'
    ),
    'add' => array(
      'func'  => '_admin_page_create',
      'perm'  => 'admin page create',
      'title' => 'Tạo trang mới',
    ),
    'edit' => array(
      'func'  => '_admin_page_edit',
      'perm'  => 'admin page edit',
      'title' => 'Chỉnh sửa nội dung trang',
    ),
    'delete' => array(
      'func'  => '_admin_page_delete',
      'perm'  => 'admin page delete'
    )
  );
}

function _admin_page_default(){
  global $database, $smarty;
  
  $aPage = array();
  $res = $database->db_query("SELECT * FROM pages ORDER BY page_id ASC");
  while ($row = $database->db_fetch_assoc($res)){
    $row['page_view_url'] = l('page/detail/'.$row['page_id']);
    $row['page_edit_url'] = l('admin_page/edit/'.$row['page_id']);
    $row['page_delete_url'] = l('admin_page/delete/'.$row['page_id']);
    
    $aPage[] = $row;
  }
  
  PGTheme::$pageTemplate = 'admin';
  $smarty->assign('aPage', $aPage);
  return $smarty->fetch('admin_page_list.tpl');
}

function _admin_page_create(){
  global $database, $smarty;
  
  if (isset($_POST['page_title'])){
    $page_title = PGRequest::getVar('page_title');
    $page_content = PGRequest::getVar('page_content');
    
    $res = $database->db_query("INSERT INTO pages(page_title, page_content, page_created) VALUES ('%s', '%s', %d)", $page_title, $page_content, time());
    if ($res){
      $page_id = $database->db_insert_id();
      url_set_alias('page/detail/'.$page_id, $page_title);
      
      cheader('admin_page/default');
    }
  }
  PGTheme::$pageTemplate = 'admin';
  __libs_ckeditor();
  return $smarty->fetch('admin_page_add.tpl');
}

function _admin_page_delete(){
  global $database;
  
  $page_id = arg(2);
  $database->db_query("DELETE FROM pages WHERE page_id=%d LIMIT 1", $page_id);
  cheader('admin_page/default');
}

function _admin_page_edit(){
  global $database, $smarty;
  
  $page_id = arg(2);
  $res = $database->db_query("SELECT * FROM pages WHERE page_id=%d LIMIT 1", $page_id);
  PGTheme::$pageTemplate = 'admin';
  __libs_ckeditor();
  
  if ($row = $database->db_fetch_assoc($res)){
    if (isset($_POST['page_title'])){
      $page_title = PGRequest::getVar('page_title');
      $page_content = PGRequest::getVar('page_content');
      
      $res = $database->db_query("UPDATE pages SET page_title='%s', page_content='%s' WHERE page_id=%d", $page_title, $page_content, $page_id);
      
      if ($res){
        url_set_alias('page/detail/'.$page_id, $page_title);
        
        cheader('admin_page/default');
      }
    }
    $smarty->assign('page', $row);
    return $smarty->fetch('admin_page_edit.tpl');
    
  }else cheader('admin_merchant/default');
}